package com.xuecheng.govern.gateway.service;

import com.xuecheng.framework.utils.CookieUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * Created by Aniymx on 2019/1/13 18:49.
 */
@Service
public class AuthService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    //从cookie查询身份令牌

    public String getTokenFromCookie(HttpServletRequest httpServletRequest) {
        Map<String, String> map = CookieUtil.readCookie(httpServletRequest, "uid");
        String token = map.get("uid");
        if (StringUtils.isEmpty(token)) {
            return null;
        }
        return token;
    }

    //从header中查询jwt令牌
    public String getJwtFromHeader(HttpServletRequest httpServletRequest) {
        String authorization = httpServletRequest.getHeader("Authorization");
        if (StringUtils.isEmpty(authorization)) {
            //拒绝访问
            return null;
        }
        if (!authorization.startsWith("Bearer ")) {
            //拒绝访问
            return null;
        }
        return authorization;
    }

    //从redis中查询令牌的过期时间
    public long getExpire(String token) {
        String key = "user_token:" + token;
        Long expire = stringRedisTemplate.getExpire(key);
        return expire;
    }


}
